import { defineStore } from 'pinia'
import router from '@/router'

export const useInternalModuleTagsViewStore = defineStore('internalModuleTagsView', {
    state: () => ({
        tagList: [],
        exclude: []
    }),
    getters: {
        include () {
            const list = this.tagList.map(tag => {
                const { menuType, isCache, _componentName } = tag.meta || {}
                if (menuType === 1 && isCache === 0) return null
                return _componentName
            }).filter(Boolean)

            return [...new Set(list)]
        }
    },
    actions: {
        addTag (tag) {
            if (this.tagList.find(item => item.meta.kid === tag.meta.kid)) return
            this.tagList.push(tag)
        },
        deleteTag (tag) {
            const index = this.tagList.findIndex(item => item.meta.kid === tag.meta.kid)
            if (index === -1) return

            const { currentRoute: { value: { meta: { kid }}}} = router
            this.tagList.splice(index, 1)

            if (tag.meta.kid === kid) {
                router.push(this.tagList[this.tagList.length - 1].fullPath)
                return
            }

            if (this.tagList.length === 1) {
                router.push(this.tagList[this.tagList.length - 1].fullPath)
                return
            }
        },
        clearTag () {
            this.tagList = []
        },
        addExclude (name) {
            if (this.exclude.includes(name)) return
            this.exclude.push(name)
        },
        deleteExclude (name) {
            const index = this.exclude.findIndex(item => item === name)
            if (index === -1) return
            this.exclude.splice(index, 1)
        },
        clearExclude () {
            this.exclude = []
        }
    }
})